import 'package:byw_blog/model/SearchHistoryModel.dart';
import 'package:byw_blog/database/SearchHitoryTable.dart';
import 'package:byw_blog/listener/OnCLickListener.dart';
import 'package:byw_blog/network/NetworkInterface.dart';
import 'package:byw_blog/pages/HomePage.dart';
import 'package:byw_blog/pages/ViewRssPage.dart';
import 'package:byw_blog/utils/AppUtil.dart';
import 'package:byw_blog/widget/ArticleListWidget.dart';
import 'package:byw_blog/widget/TagWidget.dart';
import 'package:flutter/material.dart';

class SearchPage extends SearchDelegate<String> implements OnCLickListener {
  var searchHistory = <SearchHistoryModel>[];
  var tags = <String>[];
  var articles = <dynamic>[];
  String type = "";

  SearchPage() {
    getTag();
    // 搜索历史
    SearchHistoryTable.queryLast10().then((item) => {
          for (var value1 in item)
            {
              value1.forEach((key, value2) {
                if (key == "value") {
                  searchHistory.add(SearchHistoryModel(
                      value2.toString(), AppUtil.getSystemTime()));
                }
              })
            }
        });
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    //Actions for app bar
    return [
      IconButton(
          icon: const Icon(Icons.clear),
          onPressed: () {
            query = '';
          }),
      IconButton(
          icon: const Icon(Icons.search),
          onPressed: () {
            showResults(context);
          })
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    //leading icon on the left of the app bar
    return IconButton(
        icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow,
          progress: transitionAnimation,
        ),
        onPressed: () {
          close(context, "null");
        });
  }

  @override
  Widget buildResults(BuildContext context) {
    // show some result based on the selection
    return articleList(context);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    // show when someone searches for something
    /// 文字发生变化搜索文章
    search(OnCLickListener.TYPE_SEARCH, query);
    return searchProposal();
  }

  @override
  ThemeData appBarTheme(BuildContext context) {
    return ThemeData(
      primaryColor: Colors.teal,
    );
  }

  @override
  void onTap(String type, String tag) {
    this.type = type;
    query = tag;
  }

  void search(String type, String value) {
    if (value.isNotEmpty) {
      if (type == OnCLickListener.TYPE_SEARCH) {
        saveHistory(value);
        NetworkInterface.search(value).then((value) {
          if (value.isNotEmpty) {
            articles.clear();
            articles.addAll(value);
          }
        });
      } else {
        NetworkInterface.getTagArticle(value).then((value) {
          if (value.isNotEmpty) {
            articles.clear();
            articles.addAll(value);
          }
        });
      }
    }
  }

  void getTag() {
    NetworkInterface.getTags().then((value) {
      tags.clear();
      tags.addAll(value);
    });
  }

  void saveHistory(String value) {
    SearchHistoryTable.delete(value).then((item) => {
          SearchHistoryTable.insert(
              SearchHistoryModel(value, AppUtil.getSystemTime()))
        });
  }

  /// 搜索历史、标签UI
  Widget searchProposal() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(10, 20, 10, 20),
      child: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Visibility(
              visible: searchHistory.isNotEmpty,
              child: const Text(
                '搜索历史',
                style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
              ),
            ),
            Visibility(
              visible: searchHistory.isNotEmpty,
              child: const SizedBox(height: 5),
            ),
            Visibility(
              visible: searchHistory.isNotEmpty,
              child: Wrap(
                children: List.generate(
                    searchHistory.length,
                    (index) => TagWeight(searchHistory[index].value,
                        listener: this, type: OnCLickListener.TYPE_SEARCH)),
              ),
            ),
            Visibility(
              visible: searchHistory.isNotEmpty,
              child: const SizedBox(height: 5),
            ),
            const Text(
              '标签',
              style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 5),
            Wrap(
              children: List.generate(
                  tags.length,
                  (index) => TagWeight(
                        tags[index],
                        listener: this,
                        type: OnCLickListener.TYPE_TAG,
                      )),
            ),
          ],
        ),
      ),
    );
  }

  Widget articleList(BuildContext context) {
    print(articles);
    // return ListView.builder(itemBuilder: itemBuilder);
    return SingleChildScrollView(
      child: Column(
        children: List.generate(
          articles.length,
          (index) => InkWell(
              onTap: () {
                clickArticle(context, articles[index]);
              },
              child: ArticleListWidget(
                  articles[index]['title'],
                  articles[index]['author'] ?? "",
                  articles[index]['category'])),
        ),
      ),
    );
  }

  clickArticle(BuildContext context, dynamic title) {
    HomePage.rss?.forEach((element) {
      if (element.title == title['title']) {
        int start = element.author!.lastIndexOf('(') + 1;
        int end = element.author!.lastIndexOf(')');
        var author = element.author?.substring(start, end);
        final feedItems = {
          'title': element.title,
          // 'content':item.content!.value,
          'creator': element.dc!.creator,
          // 'image':item.media!.contents![0].url,
          'link': element.link,
          'pubDate': element.pubDate,
          'author': author,
          'content': element.content!.value
        };
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => ViewRssPage(RssFeed: feedItems)));
        return;
      }
    });
  }
}
